import { loginByPwd, logOut, getUserInfo } from "api/auth";
import router, { asyncRouterMap, constantRouterMap } from '../../router';
import {getPermissions} from 'utils/menus.js'
import {hasPermission} from 'utils/sift';

const auth = {
    state:{
        store_token: sessionStorage.getItem('yunhua-admin-token'),
        store_user_info: sessionStorage.getItem('yunhua-admin-uinfo'),
        store_name:'',
        store_phone:'',
        store_permissions:[],
        store_routers:constantRouterMap,
        store_add_routers: [],
    },
    mutations:{
        SET_STORE_TOKEN: (state, store_token) => {
            state.store_token = store_token;
        },
        SET_STORE_UINFO: (state, store_user_info) => {
            state.store_user_info = store_user_info;
        },
        SET_STORE_NAME: (state, store_name) => {
            state.store_name = store_name;
        },
        SET_STORE_PHONE: (state, store_phone) => {
            state.store_phone = store_phone;
        },
        SET_STORE_PERMISSIONS: (state, store_permissions) => {
            state.store_permissions = store_permissions;
        },
        SET_STORE_ROUTERS: (state, store_routers) => {
            state.store_add_routers = store_routers;
            state.store_routers = constantRouterMap.concat(store_routers);
        },
        SET_STORE_ADD_ROUTERS: (state, store_add_routers) => {
            state.store_add_routers = store_add_routers;
        },
    },
    actions:{
          /**
         * ! 验证码登录
         */
        Login({ commit }, userInfo) {
            const username = userInfo.username.trim().replace(/\s+/g, "");
            return new Promise((resolve, reject) => {
                loginByPwd({
					username, 
					password: userInfo.password, 
					type: userInfo.type, 
                    
				}).then(response => {
                    const data = response.data.data;
                    let store_user_id = data.id;
                    sessionStorage.setItem('yunhua-admin-uinfo', JSON.stringify(data));
                    sessionStorage.setItem('yunhua-admin-token', store_user_id);
                    commit('SET_STORE_TOKEN', store_user_id);
					commit('SET_STORE_UINFO', JSON.stringify(data));
                    resolve(response.data);
                }).catch(error => {
                    reject(error);
                });
            });
        },
         /**
         * ! 退出登录
         */
        Logout({ commit, state  },id){
            return new Promise((resolve, reject) => {
                logOut(id).then(res => {
                    commit('SET_STORE_TOKEN', '');
                    commit('SET_STORE_UINFO', '');
                    commit('SET_STORE_NAME', '');
                    commit('SET_STORE_PHONE', '');
                    commit('SET_STORE_PERMISSIONS', []);
                    commit('SET_STORE_ROUTERS', constantRouterMap);
                    sessionStorage.removeItem('yunhua-admin-uinfo');
                    sessionStorage.removeItem('yunhua-admin-token');
                    router.replace({path: '/login'});
                    resolve();
                })
            })

        },
          /**
         * ! 获取用户信息
         */
        GetUserInfo({commit}){
            return new Promise((resolve, reject) => {
                let uId = sessionStorage.getItem('yunhua-admin-token');
                if(uId){
                    getUserInfo(uId).then(response => {
                        let data = response.data.data;
                        commit('SET_STORE_NAME', data['name']);
                        commit('SET_STORE_PHONE', data['phone']);
                        let permissions = getPermissions();
                        if (!permissions.length) {
                            alert('您当前登录的账号没有任何系统操作权限,请联系管理员');
                            reject(400);
                        }
                        commit('SET_STORE_PERMISSIONS', permissions);
                        resolve(Object.assign(data, { permissions: permissions }));
                    }).catch(error => {
                        reject(error);
                    });

                }else{
                    reject(400);
                }
            })

        },
         /**
         * ! 组装路由
         */
        FormatRoutes({commit},data){
              return new Promise((resolve,reject) => {
                const  permissions = data;
                const accessedRouters = asyncRouterMap.filter(v => {
                    if (hasPermission(permissions, v)) {
                         if(v.children && v.children.length > 0){
                            v.children = v.children.filter(child => {
                                if(hasPermission(permissions,child)){
                                    if(child.children && child.children.length > 0){
                                        child.children = child.children.filter(_child => {
                                             if(hasPermission(permissions,_child)){
                                                 return _child
                                             }
                                             return false
                                        })
                                   }
                                   return child

                                }
                                return false
                            })

                         }
                         return v
                    }
                    return false
                })
                accessedRouters.forEach(item => {
                    if (!item.redirect && item.children && item.children.length) {
                        item.redirect = item.children[0]['path'];
                    }
                });
                commit('SET_STORE_ROUTERS', accessedRouters.concat([{ 
                    path: '*', // 页面不存在的情况下会跳到404页面
                    redirect: '/error',
                    name: 'notFound',},
                ]));
                resolve();
              })
        }

    }
}
export default auth;